package newpackage;


import java.io.BufferedOutputStream;
import java.sql.Statement;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet to handle File upload request from Client
 * @author Javin Paul
 */
public class FileUploadHandler extends HttpServlet 
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private  String UPLOAD_DIRECTORY = "main";
        private  String UPLOAD_DIRECTORY1 = "sub";
        private  String UPDATE_DIRECTORY = "update";
        private  String UPDATE_DIRECTORY1 = "update1";
        private  String READ_DIRECTORY = "read";
        private  String READ_DIRECTORY1 = "read1";
        private  String Splitted_file;
        private  String Splitted_file1;
        private  String Splitted_file2;
  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      ServletContext context=request.getServletContext();
    //  UPLOAD_DIRECTORY=context.getInitParameter("file-upload");
        //process only if its multipart content
       String name="";
        File file1 = new File(context.getRealPath("/") +"/"+UPLOAD_DIRECTORY );
	if (!file1.exists()) {
		if (file1.mkdir()) 
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
        File file2 = new File(context.getRealPath("/") +"/"+UPLOAD_DIRECTORY1 );
	if (!file2.exists()) {
		if (file2.mkdir())
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
                
        File file3 = new File(context.getRealPath("/") +"/"+UPDATE_DIRECTORY );
	if (!file3.exists()) {
		if (file3.mkdir()) 
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
            File file4 = new File(context.getRealPath("/") +"/"+READ_DIRECTORY );
	if (!file4.exists()) {
		if (file4.mkdir()) 
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
        
               File file5 = new File(context.getRealPath("/") +"/"+READ_DIRECTORY1 );
	if (!file5.exists()) {
		if (file5.mkdir()) 
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}  
        
                File file6 = new File(context.getRealPath("/") +"/"+UPDATE_DIRECTORY1 );
	if (!file6.exists()) {
		if (file6.mkdir()) 
                {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}  
      //Starting Time
        long startTime = System.nanoTime();


        
      if(ServletFileUpload.isMultipartContent(request))
      {
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
              
                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                         name = new File(item.getName()).getName();
                        item.write( new File(context.getRealPath("/") +"/"+UPLOAD_DIRECTORY + File.separator + name));
                       //  item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                       Splitted_file=context.getRealPath("/").replace("\\","/")+UPLOAD_DIRECTORY + "/" + name;
                       Splitted_file1=context.getRealPath("/").replace("\\","/")+UPDATE_DIRECTORY + "/" + name;
                       Splitted_file2=context.getRealPath("/").replace("\\","/")+UPDATE_DIRECTORY1 + "/" + name;
                    }
                }
                for(FileItem item1 : multiparts){
                    if(!item1.isFormField()){
                         name = new File(item1.getName()).getName();
                        item1.write( new File(context.getRealPath("/")+"/"+UPLOAD_DIRECTORY1 + File.separator + name));
                      
                    }
                }
                
                   for(FileItem item1 : multiparts){
                    if(!item1.isFormField()){
                         name = new File(item1.getName()).getName();
                        item1.write( new File(context.getRealPath("/")+"/"+UPDATE_DIRECTORY+ File.separator + name));
                      
                    }
                }  
                           for(FileItem item1 : multiparts){
                    if(!item1.isFormField()){
                         name = new File(item1.getName()).getName();
                        item1.write( new File(context.getRealPath("/")+"/"+UPDATE_DIRECTORY1+ File.separator + name));
                      
                    }
                }  
      Random random = new Random();
      int rand= random.nextInt((10 - 1) + 1) + 1;
     String readSite="";
      if(rand<=5)
      {           
                           
                           for(FileItem item1 : multiparts){
                    if(!item1.isFormField()){
                         name = new File(item1.getName()).getName();
                        item1.write( new File(context.getRealPath("/")+"/"+READ_DIRECTORY1+ File.separator + name));
                      readSite=READ_DIRECTORY1;
                    }
                }  
      }
      else
      {
                   for(FileItem item1 : multiparts){
                    if(!item1.isFormField()){
                         name = new File(item1.getName()).getName();
                        item1.write( new File(context.getRealPath("/")+"/"+READ_DIRECTORY+ File.separator + name));
                      readSite=READ_DIRECTORY;
                    }
                } 

      }
     
                long stopTime = System.nanoTime();
                long duration =stopTime - startTime;
                Date d=new Date();
                SimpleDateFormat sd=new SimpleDateFormat("yyyy/MM/dd HH:mm");
                String datetime=sd.format(d);
                String execution_time="insert into file_performance (file_name,execution_time) values ('"+Splitted_file+"','"+duration+"')";
                
                String updated_value="insert into update_values(name,version,ReadSite,time_stamp) values('"+Splitted_file+"',"+0+",'"+readSite+"','"+datetime+"')";
                System.out.println(updated_value);
                HttpSession session=request.getSession();
                
                
                //Get user details
                File file=new File(Splitted_file);
               // String key1=file.getName();
//                DESKeySpec dks = new DESKeySpec(key1.getBytes());
//                SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
//		SecretKey desKey = skf.generateSecret(dks);
                
                int private_key=file.getName().hashCode();
            
                                     
                
                String secret_key=Long.toString(file.length());
                String public_key=Integer.toString(file.hashCode());
                double key=Math.random()*1000000;
           //     int k=(int)key;
               
                
                String[] token=SplitFileExample.split(Splitted_file);
                SplitFileExample.split(Splitted_file1);
                SplitFileExample.split(Splitted_file2);
                
                 Connection con=ConnectionFactory.getConnection();
                 Statement s=con.createStatement();
                // HttpSession session=request.getSession();
                 String user="";
                 if(session.getAttribute("user_name")!=null)
                {
                     user=(String)session.getAttribute("user_name");
                }
                 session.setAttribute("file_name",Splitted_file);
                 
               /*  String query="INSERT INTO FILE_DETAILS(owner,filename,private_key,public_key,secret_key,split1,split2,split3) "
                  + "VALUES('"+user+"','"+Splitted_file+"','"+private_key+"','"+public_key+"','"+secret_key+"','"+token[0]+"','"+token[1]+"','"+token[2]+"')";
                 */
                String query="INSERT INTO file_details(owner,filename,private_key,public_key,secret_key,split1,split2,split3) "
                  + "VALUES('"+user+"','"+Splitted_file+"','"+private_key+"','"+public_key+"','"+secret_key+"','"+token[0]+"','"+token[1]+"','"+token[2]+"')";
                
                s.addBatch(execution_time);
                
                //store the updated time in update_values table 
                 s.addBatch(updated_value);
                
                s.addBatch(query);
                s.executeBatch();
               // s.execute(query);
                request.setAttribute("message", "File Uploaded");
               }catch (Exception ex) {
               request.setAttribute("message", "File Upload Failed due to " + ex);
               ex.printStackTrace();
            }          
         
        }else{
            request.setAttribute("message",
                                 "Sorry this Servlet only handles file upload request");
        }
    
        request.getRequestDispatcher("/result.jsp").forward(request, response);
     
    }
    

  
}